#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Turbidsoul Chen
# @Date:   2015-05-13 09:44:55
# @Last Modified 2015-06-14


from bottle import run, route, static_file
import json
import requests
from bs4 import BeautifulSoup
import re


websiteinfos = {
    'qiushi_hot': {
        'name': '糗事百科',
        'url': 'qiushi_hot',
        'url_template': 'http://www.qiushibaike.com/hot/page/%d'
    },
    'tieba': {
        'name': '百度贴吧',
        'url': 'tieba',
        'url_template': 'http://tieba.baidu.com/f?kw=%s&ie=utf-8&pn=%d&statsInfo=frs_pager'
    },
    'taobaomm': {
        'name': '淘女郎',
        'url': 'taobaomm',
        'url_template': 'http://mm.taobao.com/json/request_top_list.htm?page=%d'
    }
    'qqinfo': {
        'name': 'QQ信息',
        'url': 'gogoqq',
        'url_template': 'http://g.gogoqq.com/'
    }
}

_headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:39.0) Gecko/20100101 Firefox/39.0'
}


@route('/')
def index():
    return static_file('index.html', root='.')


@route('/app/<filepath:path>')
def app_js(filepath):
    return static_file(filepath, root='./app')


@route('/websites')
def websites():
    return json.dumps(websiteinfos)


@route('/website/qiushi_hot')
@route('/website/qiushi_hot/<page:int>')
def qiushi_hot(page=1):
    website = websiteinfos['qiushi_hot']
    response = requests.get(website['url_template'] % 1, headers=_headers)
    if response.status_code != 200:
        return json.dumps({'message': 'Can not request Qiushibaike hot post'})
    root = BeautifulSoup(response.text)
    articles = root.select('.article')
    articlelst = []
    for article in articles:
        author = article.select('.author > a')[1].text.strip() if len(article.select('.author > a')) == 2 else None
        content = article.select(".content")[0].text.strip()
        img = article.select('.thumb > a > img')[0]['src'] if len(article.select('.thumb > a > img')) == 1 else None
        articlelst.append({
                          'author': author,
                          'content': content,
                          'img': img
                          })
    qiushidict = {
        'items': articlelst
    }
    return json.dumps(qiushidict)


@route('/website/tieba')
@route('/website/tieba/<keyword>')
@route('/website/tieba/<keyword>/<page:int>')
def tieba(keyword=None, page=1, num_per_page=50):
    if keyword:
        website = websiteinfos['tieba']
        url = website['url_template'] % (keyword, num_per_page * (page - 1))
        response = requests.get(url, headers=_headers)
        if response.status_code != 200:
            return json.dumps({'message': 'Can not request Baidu tieba hot post'})
        html = BeautifulSoup(response.text)
        postlst = html.select('#thread_list > li')
        articlelst = []
        last = int(dict([(pq.split("=")) for pq in html.select('.last')[0]['href'].split('&')])['pn'])
        print(last)
        data = {
            'page': page,
            'last': last // num_per_page,
            'keyword': keyword
        }
        for post in postlst:
            titles = post.select('.threadlist_title > a')
            if len(titles) == 0:
                continue
            titleele = titles[0]
            title = titleele['title']
            href = titleele['href']
            articlelst.append({'title': title, 'href': 'http://tieba.baidu.com' + href})
        data['items'] = articlelst
        return json.dumps(data)
    else:
        return

@route('/website/taobaomm')
@route('/website/taobaomm/<page:int>')
def taobaomm(page=1):
    website = websiteinfos['taobaomm']
    response = requests.get(website['url_template'] % page)
    if response.status_code != 200:
        return json.dumps({'message': 'Can not request Taobao top mm'})
    root = BeautifulSoup(response.text)
    elist = root.select('div.list-item')
    items = []
    for e in elist:
        ladyname = e.select('.lady-name')[0]
        item = {}
        item['name'] = ladyname.text
        item['url'] = ladyname['href']
        img = e.select('.lady-avatar img')[0]['src']
        r = re.compile(r'_\d+x\d+\.')
        item['img'] = r.sub('_300x300.', img)
        items.append(item)
    return json.dumps({'items': items, 'page': page})


if __name__ == '__main__':
    run(host='127.0.0.1', port=8080, debug=True, reloader=True)
